# --**coding:utf-8**--

import os, zipfile, shutil

import configInfo


def getBaseApkPath():
    """ 
    :return: 获取母包路径
    """
    baseApkPath = []  # 获取母包路径
    for root, dirs, files in os.walk('./baseapk'):
        for file in files:
            if os.path.splitext(file)[1] == '.apk':
                baseApkPath.append(os.path.join(root, file))
    return baseApkPath


def getBaseApkName():
    """
    :return: 获取母包name
    """
    baseApkName = []  # 获取母包文件名
    for root, dirs, files in os.walk('./baseapk'):
        for file in files:
            if os.path.splitext(file)[1] == '.apk':
                baseApkName.append(os.path.join('', file))
    return baseApkName


def addSourcedFile(apkFilePath, channelCode):
    """
    :return:添加渠道文件至apk
    """
    # apkfile 对象 --> open file
    apkFile = zipfile.ZipFile(apkFilePath, 'a', zipfile.ZIP_DEFLATED)
    # 获取sourced.dat
    fileName = getsourcedFile(channelCode)
    apkFile.write(fileName, configInfo.srcPath)
    apkFile.close()


def getsourcedFile(channelCode):
    # 写入渠道号
    if channelCode:
        fileName = 'sourceid.dat'
        file = open(fileName, 'wr+')
        file.writelines(channelCode)
        file.close()
        return fileName
    else:
        return u'channelCode is not exit'


def copyFile(srcFile, destFolder):
    # copy baseapk --> channelApk
    try:
        shutil.copy(srcFile, destFolder)
    except Exception as ex:
        print ex
        exit(1)


def dirExit(path):
    # 检查文件夹是否存在，不存在-->创建
    try:
        if not os.path.exists(path):
            os.mkdir(path)
    except Exception as ex:
        print ex


def signApk(keystorePath, signPasswd, signApk, unsignApk, alias):
    '''
    jarsigner - keystore android.keystore - storepass 123456 - signedjar android_signed.apk android.apk bieming
    '''
    # 签名
    cmd = 'jarsigner -verbose  -sigalg MD5withRSA -digestalg SHA1 -keystore ' + keystorePath + ' -storepass ' + signPasswd + ' -signedjar ' + signApk + ' ' + unsignApk + ' ' + alias
    # 执行命令  keystore path
    os.popen(cmd)


def deleteReinforceApk(apkPath):
    # 删除加固包，保留签名后的渠道包
    cmd = 'rm -rf' + ' ' + apkPath
    os.popen(cmd)


def getVersionFromFile():
    """
    :return: 版本号
    """
    try:
        version = ''
        with open('versionFile.txt') as file:
            version = file.readline()
        return version

    except IOError as ext:
        print ext


def creatVerFol():
    # 创建对应版本文件夹
    dirExit(configInfo.historyDownloadDir + getVersionFromFile())
    return '执行完毕!'
    pass

def baseApkManage():  # 历史版本母包管理

    # 创建对应版本母包文件夹
    baseApkFolder = './static/baseApkFolder/'
    if not os.path.exists(baseApkFolder):
        os.mkdir(baseApkFolder)
    baseApkArchive = baseApkFolder + getVersionFromFile() + '/'

    if not os.path.exists(baseApkArchive):
        os.mkdir(baseApkArchive)

    # copy baseapk/apk --> baseApkFolder 实现历史版本母包存储
    copyFile(getBaseApkPath()[0], baseApkArchive)

def channelApkMange():  # 历史渠道包管理

    channelApkPath = './static/hisChannelApkDir/'
    if not os.path.exists(channelApkPath):
        os.mkdir(channelApkPath)
    channelApkArchive = channelApkPath + getVersionFromFile() + '/'

    if not os.path.exists(channelApkArchive):
        os.mkdir(channelApkArchive)
    # channelapkName:视图函数构建完渠道包后传入函数

    srcChannelApk = './static/preChannelApkDir/'
    # get all apk name --> os.listdir()
    channelDirList = os.listdir(srcChannelApk)
    for i in range(0, len(channelDirList)):
        path = os.path.join(srcChannelApk, channelDirList[i])
        if os.path.isfile(path):
            copyFile(path, channelApkArchive)
        else:
            print 'channel apk XXXX fail'

def baseApkDelete():
    # baseapk目录只存储当次构建上传的母包，每次构建完毕删除当次上传母包
    try:
        os.remove(getBaseApkPath()[0])
    except Exception as error:
        print 'delete fail'

def channelApkDelete():
    # get all channnel apk from pre
    try:
        preChannelApkList = os.listdir(configInfo.presentChannelApkPath)
        print preChannelApkList
        for apkIndex in range(len(preChannelApkList)):
            eachChannelApkName = preChannelApkList[apkIndex]
            os.remove(configInfo.presentChannelApkPath+eachChannelApkName)
    except OSError as e:
        print e